package com.yueya.basic.user.service;

import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.yueya.basic.dept.model.DeptUser;
import com.yueya.basic.user.model.User;
import com.yueya.basic.user.model.UserBase;
import com.yueya.common.util.DateUtil;
import com.yueya.common.util.Encrypt;
import com.yueya.common.util.PinyinUtil;
import com.yueya.common.util.RandomUtil;
import com.yueya.common.util.UUIDGenerator;

/**
 * 用户业务类
 * 
 * @author yangfeng
 * 
 */
public class UserService {

	public Page<Record> pagination(int pageNumber, int pageSize, Map<String, Object> map) {

		String select = "select u.*,ub.*,(select d.dept_name from t_dept_user du left join t_dept d on d.dept_id = du.dept_id where du.user_id = u.user_id ) as dept_name";
		StringBuffer sb = new StringBuffer(
				" from t_user u left join t_user_base ub on ub.user_id = u.user_id where u.del_flag='0' and u.login_name != 'admin' ");

		if (map.get("name") != null && !"".equals(map.get("name"))) {
			sb.append("and ( u.USER_NO like '%" + map.get("name").toString().trim() + "%' or u.USER_NAME like '%"
					+ map.get("name").toString().trim() + "%') ");
		}
		if (map.get("deptstr") != null && !"".equals(map.get("deptstr"))) {
			sb.append(
					"and u.user_id in (select user_id from t_dept_user where dept_id = '" + map.get("deptstr") + "') ");
		}
		if (map.get("statusstr") != null && !"".equals(map.get("statusstr"))) {
			sb.append("and u.USER_STATUS = '" + map.get("statusstr") + "' ");
		}

		sb.append("  order by u.order_id asc,u.user_status desc,u.create_time asc");

		String sql = sb.toString();
		Page<Record> page = Db.paginate(pageNumber, pageSize, select, sql);

		return page;

	}

	/**
	 * 用户名密码认证身份
	 * 
	 * @param name
	 * @param pwd
	 * @return User
	 */
	public User authentication(String name, String pwd) {
		String sql = "select * from t_user a where a.user_status='1' and a.del_flag = '0' and a.LOGIN_NAME = ?";
		System.out.println(sql);
		List<User> list = User.dao.find(sql, name);
		if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				User user = (User) list.get(i);
				String password = user.getStr("pwd");
				if (Encrypt.equalsByMD5(password, pwd)) {
					return user;
				}
			}
		}

		return null;
	}

	/**
	 * 修改密码
	 * 
	 * @param name
	 * @param oldPwd
	 * @param newPwd
	 * @return boolean
	 */
	@Before(Tx.class)
	public boolean modifyPwd(String name, String oldPwd, String newPwd) {
		boolean state = false;
		User user = authentication(name, oldPwd);
		if (user != null) {
			user.set("PASSWORD", Encrypt.doStrByMD5(newPwd));
			state = user.update();
		}
		return state;
	}

	/**
	 * 修改密码
	 * 
	 * @param user
	 * @return
	 */
	@Before(Tx.class)
	public boolean modifyPwd(User user) {
		boolean state = false;
		if (user != null) {
			user.set("PASSWORD", Encrypt.doStrByMD5(user.getStr("PASSWORD")));
			state = user.update();
		}
		return state;
	}

	public Record getUserByLoginName(String loginName) {
		Record record = Db.findFirst("select * from t_user i where i.login_name ='" + loginName + "'");
		return record;
	}

	public Record getUserById(String id) {
		String sql = "select * from t_user u left join t_user_ext e on e.user_id = u.user_id "
				+ "where  u.del_flag = '0' and u.user_id = '" + id + "'";
		Record r = Db.findFirst(sql);
		String picUrl = "";
		r.set("url", picUrl + r.getStr("url"));
		return r;
	}

	public List<User> getUserListByDeptId(String deptId) {
		String sql = "select u.* from t_user u left join t_dept_user du on du.user_id = u.user_id where u.del_flag='0' and du.dept_id = '"
				+ deptId + "' order by convert(u.user_name using gbk) collate gbk_chinese_ci asc";

		return User.dao.find(sql);
	}

	public int getUserCount(String deptId) {
		int num = getUserListByDeptId(deptId).size();
		return num;
	}

	/**
	 * 通过用户id获得用户级别最高级别
	 * 
	 * @return
	 */
	public int getLevelByUserid(String userid) {
		Integer level = 99999;

		String sql = "select  MIN(level) level  from t_role  where id in (select role_id from t_role_user where user_id=?)";
		Record record = Db.findFirst(sql, userid);
		level = (Integer) (record.get("level") == null ? level : record.get("level"));
		return level;
	}

	public int getUserNumByDeptId(String pid) {
		String sql = "select id from t_user where dept_id = '" + pid + "' and del_flag = '0' and status = '1'";
		List<Record> list = Db.find(sql);
		if (list != null && list.size() > 0) {
			return list.size();
		}
		return 0;
	}

	public List<Record> getUserinfoAndDept() {

		String sql = "select a.id,concat(a.user_name ,'(',b.dept_name,')') user_info ,a.dept_id ,b.parent_id from t_user a left join t_dept b on a.dept_id = b.id  where a.status=1 and a.del_flag=0 order by b.dept_name";
		List<Record> list = Db.find(sql);

		return list;

	}

	/**
	 * 判断用户名是否已经存在,存在为true 否则false
	 * 
	 * @param login_name
	 * @return
	 */
	public boolean isExistLogin_name(String login_name) {
		String sql = "select * from t_user where login_name=? and user_id!=?";
		List<User> li = User.dao.find(sql, login_name);
		if (li != null && li.size() > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 保存
	 * 
	 * @param user
	 * @param userExt
	 * @return
	 */
	@Before(Tx.class)
	public boolean save(User user, UserBase userBase, DeptUser deptUser) {
		boolean bl = false;

		if (user.getStr("user_id") != null && !"".equals(user.getStr("user_id"))) {
			user.set("user_pinyin", PinyinUtil.pinyingToUpper(PinyinUtil.hanziToPinyin(user.getStr("user_name"), "")));
			user.set("update_time", DateUtil.getDate(DateUtil.timeFormat));
			if (userBase.get("URL") != null) {
				String picUrl = "";
				String url = userBase.get("URL");
				url = url.replace(picUrl, "");
				userBase.set("URL", url);
			}
			userBase.update();
			bl = user.update();
		} else {
			String user_id = UUIDGenerator.getUUID();
			String create_time = DateUtil.getDate(DateUtil.timeFormat);
			user.set("user_id", user_id);
			user.set("user_pinyin", PinyinUtil.pinyingToUpper(PinyinUtil.hanziToPinyin(user.getStr("user_name"), "")));
			user.set("create_time", create_time);
			String pwd = RandomUtil.getLetterNumber(6);
			String enPwd = Encrypt.doStrByMD5(pwd);
			user.set("init_pwd", pwd);
			user.set("pwd", enPwd);
			if (user.getStr("login_name") == null || "".equals(user.getStr("login_name"))) {
				user.set("login_name", PinyinUtil.hanziToPinyin(user.getStr("user_name"), ""));
			}
			bl = user.save();

			userBase.set("user_base_id", UUIDGenerator.getUUID());
			userBase.set("user_id", user_id);
			if (userBase.get("URL") != null) {
				String picUrl = "";
				String url = userBase.get("URL");
				url = url.replace(picUrl, "");
				userBase.set("URL", url);
			}
			userBase.set("create_time", create_time);
			bl = userBase.save();

			deptUser.set("dept_user_id", UUIDGenerator.getUUID()).set("user_id", user_id);
			bl = deptUser.save();

		}

		return bl;
	}

	/**
	 * 初始化全部密码,除超级管理员外
	 * 
	 * @return
	 */
	@Before(Tx.class)
	public boolean initAllPwd() {
		boolean bl = false;
		List<User> list = User.dao.find(
				"select id,password,user_name from t_user where del_flag = '0' and status='1' and login_name != 'admin'");
		User u = null;
		String pwd = "";
		for (int i = 0; i < list.size(); i++) {
			u = (User) list.get(i);
			pwd = RandomUtil.getLetterNumber(6);
			u.set("password", Encrypt.doStrByMD5(pwd));
			u.set("pwd", pwd);
			bl = u.update();
		}

		return bl;
	}
}
